import * as Cesium from '@cesiumjs';

const utils = {}

const EMPTY_OBJECT = {};

function defineProperties(primitive) {
  Object.defineProperty(primitive, "name", {
    get() {
      return primitive._name || "未命名"
    },
    set(val) {
      primitive._name = val
    }
  })
  Object.defineProperty(primitive, "title", {
    get() {
      return primitive._title || primitive._name
    },
    set(val) {
      primitive._title = val
    }
  })
}

function updateProps(primitive, options) {
  if (!primitive) return;

  defineProperties(primitive)

  options = options || EMPTY_OBJECT;
  for (let k in options) {
    primitive.hasOwnProperty(k) && (primitive[k] = options[k])
  }

  !primitive.guid && (primitive.guid = Cesium.createGuid());
}

utils.add = function(viewer, lyrDefine, readyCallback) {
  if (viewer && lyrDefine && lyrDefine.type === 'tileset') {
    const {
      options,
      url
    } = lyrDefine;

    if (!url) {
      console.error("url不能为空！");
      return true;
    }

    var tileset = new Cesium.Cesium3DTileset({
      url
    });

    const primitive = viewer.scene.primitives.add(tileset);

    updateProps(primitive, options)

    tileset.readyPromise
      .then(function(tileset) {
        readyCallback && readyCallback(tileset,viewer)
      })
      .otherwise(function(error) {
        console.error(error);
      });

    return primitive;
  }

  return false;
}

utils.ObjectSchema = {

}

const tilesetUtils = utils;

export {
  tilesetUtils
}
